package com.wmz.config.handler;


import com.wmz.constant.Constants;
import com.wmz.entity.User;
import com.wmz.result.R;
import com.wmz.service.RedisService;
import com.wmz.util.JSONUtils;
import com.wmz.util.JWTUtils;
import com.wmz.util.ResponseUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.TimeUnit;


@Component
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Resource
    private RedisService redisService;
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //由于禁用了session，我们在登录成功后，需要在服务器保持用户的登录状态，前端下次来访问服务器端的时候，服务器端要知道这个人登录了
        User user = (User) authentication.getPrincipal();

        //1、生成jwt
        //把user对象转成json
        String userJson = JSONUtils.toJSON(user);
        String jwt = JWTUtils.createJWT(userJson);

        //2、写入Redis
        redisService.setValue(Constants.REDIS_JWT_KEY + user.getId(),jwt);

        //3、设置jwt不同过期时间（选择记住我，过期是10天，否则是2天）
        String remeberMe = request.getParameter("remeberMe");
        if(Boolean.parseBoolean(remeberMe)){
            redisService.expire(Constants.REDIS_JWT_KEY + user.getId(),Constants.EXPIRE_TIME, TimeUnit.SECONDS);
        }else {
            redisService.expire(Constants.REDIS_JWT_KEY + user.getId(),Constants.DEFAULT_EXPIRE_TIME, TimeUnit.SECONDS);
        }

        //登录成功的统一结果
        R result = R.OK(jwt);

        //把R对象转成json
        String resultJSON = JSONUtils.toJSON(result);

        //把json写出去，写到浏览器
        ResponseUtils.write(response, resultJSON);
    }
}
